//禁止右键和刷新
$(document).ready(function() {
	$(document).bind("contextmenu", function(e) {
		return false;
	}).bind("keydown", function(e) {
		e = window.event || e;
		if (e.keyCode == 116) {
			e.keyCode = 0;
			return false;
		}
	});
});

String.prototype.startWith=function(str){     
	  var reg=new RegExp("^"+str);     
	  return reg.test(this);        
	}  

String.prototype.endWith=function(str){     
var reg=new RegExp(str+"$");     
return reg.test(this);        
}

String.prototype.decode = function(){
	var n = arguments.length;
    for (var i = 0; i < n-1; i++) {
    	if(i%2 == 0 && arguments[i] == this){
    		return arguments[i+1];
    	}
    }
    if(n%2 == 1){
    	return arguments[n-1];
    }
  return this;
}

Date.prototype.format = function(format) {
	if(this.getTime()==0)return "";
	var o = {
		"M+" : this.getMonth() + 1, // month
		"d+" : this.getDate(), // day
		"h+" : this.getHours(), // hour
		"m+" : this.getMinutes(), // minute
		"s+" : this.getSeconds(), // second
		"q+" : Math.floor((this.getMonth() + 3) / 3), // quarter
		"S" : this.getMilliseconds()
	// millisecond
	}
	if (/(y+)/.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + "")
				.substr(4 - RegExp.$1.length));
	}
	for ( var k in o) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
					: ("00" + o[k]).substr(("" + o[k]).length));
		}
	}
	return format;
}
/**
 * 工具组件 对原有的工具进行封装，自定义某方法统一处理
 * 
 */
;
(function() {
	ly = {};
	ly.ajax = (function(params) {
		var pp = {
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				
			}
		};
		$.extend(pp, params);
		$.ajax(pp);
	});
	ly.ajaxSubmit = (function(form, params) {// form 表单ID. params ajax参数
		var pp = {
			error : function(XMLHttpRequest, textStatus, errorThrown) {
			}
		};
		$.extend(pp, params);
		$(form).ajaxSubmit(pp);
	});
	lay = {
			validate : function(form){
				//自定义验证规则
				  form.verify({
				    word: function(value, item){
				    	if(!/[a-zA-Z0-9]+/.test(value)){
				    		return '请输入字母或数字';
				    	}
				    } ,
				    price: function(value, item){
				    	if(!/^(([1-9]{1}[0-9]{0,10})|0)[.]{0,1}[0-9]{0,2}$/.test(value)){
				    		return "请输入金额";
				    	}
				    },
				    float : function(value, item){
				    	if(!/^(([1-9]{1}[0-9]{0,10})|0)[.]{0,1}[0-9]{0,2}$/.test(value)){
				    		return "请输入数字";
				    	}
				    },
				    percent : function(value, item){
				    	if(!/^([1-9][0-9]|[0-9])%$/.test(value)){
				    		return "请输入不带小数的百分比";
				    	}
				    },
				  });
			},
			exportData : function(path,table,fileName){

				var form=$("<form>");//定义一个form表单
				form.attr("style","display:none");
				form.attr("target","");
				form.attr("method","post");
				form.attr("action",path);
				$("body").append(form);//将表单放置在web中
				var input1=$("<input>");
				input1.attr("type","hidden");
				input1.attr("name","exportData");
				input1.attr("value",JSON.stringify(table["cols"][0]));
				form.append(input1);
				if(fileName){
					var input1=$("<input>");
					input1.attr("type","hidden");
					input1.attr("name","fileName");
					input1.attr("value",fileName);
					form.append(input1);
				}
				var para = table["where"]
				for(var p in para){
					var input1=$("<input>");
					input1.attr("type","hidden");
					input1.attr("value",para[p]);
					input1.attr("name",p);
					form.append(input1);
				}
				form.submit();//表单提交 
			
			},
	}
	dict = {

		getName : function(code) {
			if (!code || code == '') {
				return '';
			}
			return common.ajax(rootPath+"/common/getFiledValue.shtml", {"className":"cn.yxcps.backstage.scm.web.base.entity.SysDictionFormMap","field":"code","showField":"name","value_":code}, "json");
			
		},
		getChildren : function(code) {
			if (!code || code == '') {
				return [];
			}
			return common.ajax(rootPath+"/common/queryList.shtml", {"className":"cn.yxcps.backstage.scm.web.base.entity.SysDictionFormMap","key":"$sql","value":" parent_id = (select id from base_dictionary_info where code  = '"+code+"')"}, "json");
		}

	}

	contact = {

		decrypt : function(v_) {

			return common.ajax(rootPath + "/common/contact/decrypt.shtml", {
				value_ : v_
			}, "json");

		},
		encrypt : function(v_) {

			return common.ajax(rootPath + "/common/contact/encrypt.shtml", {
				value_ : v_
			}, "json");

		},
		area : function(v_) {
			return common.ajax(rootPath + "/common/contact/area.shtml", {
				value_ : v_
			}, "json");
		},
		isNative : function(v_) {
			return common.ajax(rootPath + "/common/contact/isNative.shtml",
					{
						value_ : v_
					}, "json");
		}

	}

	common = {
		/**
		 * ajax同步请求 返回一个html内容 dataType=html. 默认为html格式 如果想返回json.
		 * CommnUtil.ajax(url, data,"json")
		 * 
		 */
		ajax : function(url, data, dataType) {
			if (!CommnUtil.notNull(dataType)) {
				dataType = "html";
			}
			var html = '没有结果!';
			// 所以AJAX都必须使用ly.ajax..这里经过再次封装,统一处理..同时继承ajax所有属性
			if (url.indexOf("?") > -1) {
				url = url + "&_t=" + new Date();
			} else {
				url = url + "?_t=" + new Date();
			}
			ly.ajax({
				type : "post",
				data : data,
				url : url,
				dataType : dataType,// 这里的dataType就是返回回来的数据格式了html,xml,json
				async : false,
				cache : false,// 设置是否缓存，默认设置成为true，当需要每次刷新都需要执行数据库操作的话，需要设置成为false
				success : function(data) {
					html = data;
				}
			});
			return html;
		},
		select : function(url, data, key, value, bindingId, first) {
			if (first) {
				$("#" + bindingId).html(
						"<option value=''>" + first + "</option>");
			} else {
				$("#" + bindingId).html("");
			}
			ly.ajax({
				type : "post",
				data : data,
				url : url,
				dataType : "json",// 这里的dataType就是返回回来的数据格式了html,xml,json
				async : false,
				cache : false,// 设置是否缓存，默认设置成为true，当需要每次刷新都需要执行数据库操作的话，需要设置成为false
				success : function(data) {
					for (var i = 0; i < data.length; i++) {
						$("#" + bindingId).append(
								"<option value='" + data[i][key] + "'>"
										+ data[i][value] + "</option>")
					}
				}
			});
		},
		getDateValue : function(df,add,d){
			var dff = !df?'yyyy-MM-dd':df;
			var dd = !d?new Date():d;
			var adds =!add?"D|0":add.split("|");
			var dt = (adds[0]);
			var d = parseInt(adds[1]);
			if(dt=='M'){
				dd.setMonth(dd.getMonth()+d);
			}else if(dt=='D'){
				dd.setDate(dd.getDate()+d);
			}else if(dt=='H'){
				dd.setHours(dd.getHours()+d);
			}
			
			var ms = dd.getMonth()+1;
			var ds = dd.getDate();
			var hs =dd.getHours();
			var dds = dff.replace("yyyy",dt=='Y'?dd.getFullYear()+d:dd.getFullYear()).replace("MM",ms>9?ms:'0'+ms).replace("dd",ds>9?ds:'0'+ds).replace("HH",hs>9?hs:'0'+hs).replace("mm",dd.getMinutes()>9?dd.getMinutes():'0'+dd.getMinutes()).replace("ss",dd.getSeconds()>9?dd.getSeconds():'0'+dd.getSeconds())
			return dds;
		},
		percent : function(d){
			return (Math.round(d * 10000)/100).toFixed(2) + '%';
		},
		/**
		 * 判断某对象不为空..返回true 否则 false
		 */
		notNull : function(obj) {
			if (obj === null) {
				return false;
			} else if (obj === undefined) {
				return false;
			} else if (obj === "undefined") {
				return false;
			} else if (obj === "") {
				return false;
			} else if (obj === "[]") {
				return false;
			} else if (obj === "{}") {
				return false;
			} else {
				return true;
			}

		},
		
		/**
		 * 判断某对象不为空..返回obj 否则 ""
		 */
		notEmpty : function(obj) {
			if (obj === null) {
				return "";
			} else if (obj === undefined) {
				return "";
			} else if (obj === "undefined") {
				return "";
			} else if (obj === "") {
				return "";
			} else if (obj === "[]") {
				return "";
			} else if (obj === "{}") {
				return "";
			} else {
				return obj;
			}

		},
		loadingImg : function() {
			var html = '<div class="alert alert-warning">'
					+ '<button type="button" class="close" data-dismiss="alert">'
					+ '<i class="ace-icon fa fa-times"></i></button><div style="text-align:center">'
					+ '<img src="' + rootPath + '/images/loading.gif"/><div>'
					+ '</div>';
			return html;
		},
		/**
		 * html标签转义
		 */
		htmlspecialchars : function(str) {
			var s = "";
			if (str.length == 0)
				return "";
			for (var i = 0; i < str.length; i++) {
				switch (str.substr(i, 1)) {
				case "<":
					s += "&lt;";
					break;
				case ">":
					s += "&gt;";
					break;
				case "&":
					s += "&amp;";
					break;
				case " ":
					if (str.substr(i + 1, 1) == " ") {
						s += " &nbsp;";
						i++;
					} else
						s += " ";
					break;
				case "\"":
					s += "&quot;";
					break;
				case "\n":
					s += "";
					break;
				default:
					s += str.substr(i, 1);
					break;
				}
			}
		},
		/**
		 * in_array判断一个值是否在数组中
		 */
		in_array : function(array, string) {
			for (var s = 0; s < array.length; s++) {
				thisEntry = array[s].toString();
				if (thisEntry == string) {
					return true;
				}
			}
			return false;
		},
		second2Time : function(second){
			var h = Math.floor(second/3600);
			var m = Math.floor((second - h*3600)/60);
			var s = Math.floor(second - h*3600 - m*60);
			return h+":"+(m>9?m:("0"+m))+":"+(s>9?s:("0"+s))
		},
	};
})();

jQuery.cookie = function(name, value, options) {
	if (typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};
		if (value === null) {
			value = '';
			options = $.extend({}, options); // clone object since it's
			// unexpected behavior if the
			// expired property were changed
			options.expires = -1;
		}
		var expires = '';
		if (options.expires
				&& (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime()
						+ (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires
			// attribute,
			// max-age is not
			// supported by IE
		}
		// NOTE Needed to parenthesize options.path and options.domain
		// in the following expressions, otherwise they evaluate to undefined
		// in the packed version for some reason...
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [ name, '=', encodeURIComponent(value), expires,
				path, domain, secure ].join('');
	} else { // only name given, get cookie
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie
							.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};

// 表单json格式化方法……不使用&拼接
(function($) {
	$.format = function(source, params) {
		if (arguments.length == 1)
			return function() {
				var args = $.makeArray(arguments);
				args.unshift(source);
				return $.format.apply(this, args);
			};
		if (arguments.length > 2 && params.constructor != Array) {
			params = $.makeArray(arguments).slice(1);
		}
		if (params.constructor != Array) {
			params = [ params ];
		}
		$.each(params, function(i, n) {
			source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
		});
		return source;
	};
	/*
	 * 调用方法 var text = "a{0}b{0}c{1}d\nqq{0}"; var text2 = $.format(text, 1, 2);
	 * alert(text2);
	 */
	$.fn.serializeJson = function() {
		var serializeObj = {};
		var array = this.serializeArray();
		$(array).each(
				function() {
					if (serializeObj[this.name]) {
						if ($.isArray(serializeObj[this.name])) {
							serializeObj[this.name].push(this.value);
						} else {
							serializeObj[this.name] = [
									serializeObj[this.name], this.value ];
						}
					} else {
						serializeObj[this.name] = this.value;
					}
				});
		return serializeObj;
	};
	
	/** jQuery往textarea中光标所在位置插入文本的方法* */
	$.fn.extend({
		insertContent : function(myValue, t) {
			var $t = $(this)[0];
			if (document.selection) { // ie
				this.focus();
				var sel = document.selection.createRange();
				sel.text = myValue;
				this.focus();
				sel.moveStart('character', -l);
				var wee = sel.text.length;
				if (arguments.length == 2) {
					var l = $t.value.length;
					sel.moveEnd("character", wee + t);
					t <= 0 ? sel.moveStart("character", wee - 2 * t
							- myValue.length) : sel.moveStart("character", wee
							- t - myValue.length);
					sel.select();
				}
			} else if ($t.selectionStart || $t.selectionStart == '0') {
				var startPos = $t.selectionStart;
				var endPos = $t.selectionEnd;
				var scrollTop = $t.scrollTop;
				$t.value = $t.value.substring(0, startPos) + myValue
						+ $t.value.substring(endPos, $t.value.length);
				this.focus();
				$t.selectionStart = startPos + myValue.length;
				$t.selectionEnd = startPos + myValue.length;
				$t.scrollTop = scrollTop;
				if (arguments.length == 2) {
					$t.setSelectionRange(startPos - t, $t.selectionEnd + t);
					this.focus();
				}
			} else {
				this.value += myValue;
				this.focus();
			}
		}
	})
})(jQuery);

/*
 * 数组元素去重
 */
if (typeof Array.prototype.distinct != "function") {
	Array.prototype.distinct = function() {
		this.sort();
		for (var i = 0; i < this.length - 1; i++) {
			if ($.isPlainObject(this[i]) && $.isPlainObject(this[i + 1])) {
				if (o2o(this[i], this[i + 1])) {
					this.splice(i, 1);
				}
			} else if ($.isArray(this[i]) && $.isArray(this[i + 1])) {
				if (a2a(this[i], this[i + 1])) {
					this.splice(i, 1);
				}
			} else if (this[i] === this[i + 1]) {
				this.splice(i, 1);
			}
		}
	}
}
/*
 * 比较对象是否相同
 */
function o2o(o1, o2) {
	if (!($.isPlainObject(o1) && $.isPlainObject(o2))) {
		return false;
	}

	var k1k2 = [], k1 = [], k2 = [];
	$.each(o1, function(k, v) {
		k1.push(k);
	});

	$.each(o2, function(k, v) {
		k2.push(k);
	});
	if (k1.length != k2.length) {
		return false;
	}
	k1k2 = k1;
	k1k2 = k1k2.concat(k2);
	k1k2.distinct();
	if (k1.length != k1k2.length || k2.length != k1k2.length) {
		return false;
	}

	var flag = true;
	$.each(k1k2, function(i, v) {
		var v1 = o1[v];
		var v2 = o2[v];
		if (typeof v1 != typeof v2) {
			flag = false;
		} else {
			if ($.isPlainObject(v1) && $.isPlainObject(v2)) {// recursion
				flag = o2o(v1, v2);
				if (!flag) {
					return false;
				}
			} else if ($.isArray(v1) && $.isArray(v2)) {
				flag = a2a(v1, v2);
				if (!flag) {
					return false;
				}
			} else {
				if (v1 !== v2) {
					flag = false;
				}
			}
		}
	});
	return flag;
}
/*
 * 比较数组是否完全相同
 */
function a2a(a1, a2) {
	if (!($.isArray(a1) && $.isArray(a2))) {
		return false;
	}
	if (a1.length != a2.length) {
		return false;
	}

	a1.sort();
	a2.sort();
	for (var i = 0; i < a1.length; i++) {
		if (typeof a1[i] != typeof a2[i]) {
			return false;
		}
		if ($.isPlainObject(a1[i]) && $.isPlainObject(a2[i])) {
			var retVal = o2o(a1[i], a2[i]);
			if (!retVal) {
				return false;
			}
		} else if ($.isArray(a1[i]) && $.isArray(a2[i])) {// recursion
			if (!a2a(a1[i], a2[i])) {
				return false;
			}
		} else if (a1[i] !== a2[i]) {
			return false;
		}
	}
	return true;
}

